package org.twf.aicodehelper.config.ai.tools;

import dev.langchain4j.agent.tool.P;
import dev.langchain4j.agent.tool.Tool;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
public class SearchTool {

    @Tool(name = "bingSearch", value = "Get information from bing.com based on keywords. " +
            "When a user requests a query or search, please use this tool to query the Internet. " +
            "The input should be a clear search term.")
    public String search(@P(value = "the keyword to search") String keyword) {
        // 检查输入参数
        if (keyword == null || keyword.trim().isEmpty()) {
            return "搜索关键词不能为空";
        }

        log.info("query: {}", keyword);

        try {
            String encodedKeyword = URLEncoder.encode(keyword, StandardCharsets.UTF_8);
            String searchUrl = "https://www.bing.com/search?q=" + encodedKeyword;

            // 使用Jsoup模拟浏览器请求，添加更多请求头以避免被反爬虫机制拦截
            Map<String, String> headers = new HashMap<>();
            headers.put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36");
            headers.put("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
            headers.put("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3");
            headers.put("Accept-Encoding", "gzip, deflate");
            headers.put("Connection", "keep-alive");
            headers.put("Upgrade-Insecure-Requests", "1");

            Document doc = Jsoup.connect(searchUrl)
                    .headers(headers)
                    .timeout(15000)
                    .get();

            // 提取搜索结果
            Elements results = doc.select("li.b_algo");
            List<String> searchResults = new ArrayList<>();

            // 获取前10个搜索结果（增加结果数量以提高准确性）
            for (int i = 0; i < Math.min(10, results.size()); i++) {
                Element result = results.get(i);
                Element titleElement = result.select("h2 a").first();
                Element descElement = result.select(".b_caption p").first();
                
                // 尝试其他可能的选择器
                if (descElement == null) {
                    descElement = result.select("p").first();
                }
                
                if (titleElement != null) {
                    String title = titleElement.text();
                    String description = descElement != null ? descElement.text() : "无描述";
                    
                    // 过滤掉明显不相关或低质量的结果
                    if (title.trim().length() > 0 && description.trim().length() > 5) {
                        searchResults.add(title + ": " + description);
                    }
                }
                
                // 如果已经收集到足够的高质量结果，则提前退出
                if (searchResults.size() >= 5) {
                    break;
                }
            }

            // 如果没有搜索结果，返回适当的提示
            if (searchResults.isEmpty()) {
                return "未找到与'" + keyword + "'相关的搜索结果";
            }

            // 构建结果字符串
            StringBuilder resultBuilder = new StringBuilder();
            resultBuilder.append("通过Bing搜索\"").append(keyword).append("\"的结果:\n\n");
            for (int i = 0; i < searchResults.size(); i++) {
                resultBuilder.append(i + 1).append(". ").append(searchResults.get(i)).append("\n");
            }

            return resultBuilder.toString();

        } catch (IOException e) {
            log.error("搜索过程中发生错误: ", e);
            return "搜索失败: " + e.getMessage();
        } catch (Exception e) {
            log.error("搜索过程中发生未预期的错误: ", e);
            return "搜索过程中发生错误: " + e.getMessage();
        }
    }

}